<template>
  <div id="main" style="width: 500px; height: 400px"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, watch, ref } from 'vue';
const props = defineProps({
  eduNeed: {
    type: Object,
    default: () => {},
  },
});
const newEduNeed = ref(null);
const filteredArray = ref(null);
watch(
  () => props.eduNeed,
  (newValue) => {
    if (newValue) {
      newEduNeed.value = newValue;
      filteredArray.value = newEduNeed.value.edu_ratioStr.filter(
        (item) => item.length > 0
      );

      handleBarChart();
    }
  }
);
const handleBarChart = () => {
  var chartDom = document.getElementById('main');
  var myChart = echarts.init(chartDom);
  var option;

  // There should not be negative values in rawData
  const rawData = filteredArray.value;
  const totalData = [];
  for (let i = 0; i < rawData[0].length; ++i) {
    let sum = 0;
    for (let j = 0; j < rawData.length; ++j) {
      sum += rawData[j][i];
    }
    totalData.push(sum);
  }
  const grid = {
    // left: 100,
    // right: 100,
    // top: 50,
    // bottom: 50,
  };
  const series = newEduNeed.value.note.map((name, sid) => {
    return {
      name,
      type: 'bar',
      stack: 'total',
      barWidth: '60%',
      label: {
        // show: true,
        // formatter: (params) => Math.round(params.value * 1000) / 10 + '%'
      },
      data: rawData[sid].map((d, did) =>
        totalData[did] <= 0 ? 0 : d / totalData[did]
      ),
    };
  });
  option = {
    title: {
      text: newEduNeed.value.subTitle,
      left: 'left',
      textStyle: {
        // color: "#999",
        // fontWeight: "normal",
        fontSize: 16,
      },
    },
    legend: {
      selectedMode: false,
      bottom: 10,
    },
    grid,
    yAxis: {
      type: 'value',
      //   type: "category",
      //   data: [0, 20, 40, 60, 80, 100],
      axisLabel: {
        formatter: (value) => {
          return value * 100 + '%';
        },
      },
    },
    xAxis: {
      type: 'category',
      data: newEduNeed.value.xMarks,
      axisLabel: {
        formatter: (value) => {
          return value + '月';
        },
      },
    },
    series,
  };

  option && myChart.setOption(option);
};
onMounted(() => {});
</script>

<style lang="scss" scoped></style>
